<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>

</body>
<script>
	class ListNode {
		constructor(value) {
			this.value = value; // 节点存储的数据
			this.next = null;   // 指向下一个节点的指针
		}
	}
	// 创建链表
	function createLinkedList(arr) {
		if (!arr.length) return null;
		const head = new ListNode(arr[0]);
		let current = head;
		for (let i = 1; i < arr.length; i++) {
			current.next = new ListNode(arr[i]);
			current = current.next;
		}
		return head;
	}
	
	// 打印链表
	function printLinkedList(head) {
		let result = "";
		let current = head;
		while (current) {
			result += current.value + " -> ";
			current = current.next;
		}
		result += "null";
		console.log(result);
	}
	{
		// 迭代法
		function reverseLinkedList(head) {
			let prev = null;    // 已反转部分的最后一个节点
			let current = head; // 当前处理的节点
			
			while (current !== null) {
				const nextTemp = current.next; // 保存当前节点的下一个节点
				current.next = prev;         // 反转当前节点的指针
				prev = current;              // 移动 prev 到当前节点
				current = nextTemp;          // 移动 current 到下一个节点
			}
			
			return prev; // 返回新的头节点
		}
		
		const list = createLinkedList([1, 2, 3, 4]);
		console.log("原链表:");
		printLinkedList(list); // 输出: 1 -> 2 -> 3 -> 4 -> null
		
		const reversedList = reverseLinkedList(list);
		console.log("反转后的链表:");
		printLinkedList(reversedList); // 输出: 4 -> 3 -> 2 -> 1 -> null
	}
	{
		// 递归法
		function reverseLinkedList(head){
			if(head === null || head.next === null){
				return head
			}
			const resultNode = reverseLinkedList(head.next)
			head.next.next = head
			head.next = null
			return resultNode
		}
		
		const list = createLinkedList([1, 2, 3, 4]);
		console.log("原链表:");
		printLinkedList(list); // 输出: 1 -> 2 -> 3 -> 4 -> null
		
		const reversedList = reverseLinkedList(list);
		console.log("反转后的链表:");
		printLinkedList(reversedList); // 输出: 4 -> 3 -> 2 -> 1 -> null
	}

</script>
</html>